package org.rbac.serv;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.rbac.po.PermissionRole;
import org.rbac.po.PermissionUserRoleRef;
import org.rbac.vo.Role;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kingschan.lang.date.TimeStampUtil;

/**
 * 角色服务
 * 
 * <pre>
 * 项目名称：rbac
 * 类名称：RoleServices
 * 类描述：角色服务
 * 创建人：唐家林(tjl)
 * 创建时间：2014-9-25 上午9:37:52
 * 修改人：
 * 修改时间：
 * 修改备注：
 * @version
 * </pre>
 */

@Service
public class RoleServices extends CommonServices {
	
	@Autowired
	private PermissionControlServices permissionControlServ;

	/**
	 * 新增一个角色数据
	 * 
	 * @param r
	 *            保存的角色数据
	 * @throws Exception
	 */
	public void saveRole(Role r) throws Exception {
		this.editRole(r, 0);
	}

	/**
	 * 修改一个角色数据
	 * 
	 * @param r
	 *            修改的角色数据
	 * @throws Exception
	 */
	public void moidifyRole(Role r) throws Exception {
		int i = 0;
		this.editRole(r, i);
	}
	
	/**
	 * 修改角色状态
	 * 
	 * @param ids
	 *            修改状态的角色数据主键
	 * @param status
	 *            状态(0:删除, 1:正常, 2:禁用)
	 * @throws Exception
	 */
	public void moidifyRoleStatus(Integer[] ids, short status) throws Exception {
		String hql = "UPDATE PermissionRole pr SET pr.RStatus = :status WHERE pr.id IN (:ids)";
			
			// 数据库操作一,此时操作在DATA_SOURCE_LOCAL数据源所指数据库生效
		Session s = getDao().getSession();
			Query q = s.createQuery(hql);
			q.setParameter("status", status);
			q.setParameterList("ids", ids);
			q.executeUpdate();
			
			//Session s200 = getDao200().getSession();
			//Query q200 = s200.createQuery(hql);
			
		/*	q200.setParameter("status", status);
			q200.setParameterList("ids", ids);
			if (q200.executeUpdate() > 0) {
//				throw new RuntimeException("如果都回滚则正确");
			}*/
		
		///getDao200().closeSession(s200);
	}

	/**
	 * 编辑角色(新增或修改)
	 * 
	 * @param r
	 *            操作的角色数据
	 */
	public void editRole(Role r, int i) {
		if (null == r) {
			return;
		}
		PermissionRole role = null;
		if (null == r.getId()) {
			role = new PermissionRole();
		} else {
			role = (PermissionRole) getDao().get(PermissionRole.class, r.getId());
		}
		// 属性值拷贝(拷贝r对象的属性值到role对象中对应名称的属性,且不拷贝id和RCdate的值)
		BeanUtils.copyProperties(r, role, new String[] { "id", "RCdate", "RStatus" });

		if (null == r.getId()) {
			role.setRCdate(TimeStampUtil.getCurrentDate());
			short status = 1;
			role.setRStatus(status);
			getDao().save(role);
		} else {
			getDao().update(role);
		}
		
		if (null != r.getAid()) {
			// 修改角色权限
			permissionControlServ.editByOneRole(role, r.getAid());
		}
	}
	
	/**
	 * 添加角色成员
	 * @param userids
	 */
	public void addRoleMember(Integer roleId,String userids){
	    String [] uids=userids.split(",");
	    String hql ="select count(*) from PermissionUserRoleRef where rfUserId=? and rfRoleId=?";
	    List<PermissionUserRoleRef> lis = new ArrayList<PermissionUserRoleRef>();
	    for (int i = 0; i < uids.length; i++) {
	        //要判断是否存在
	        Long total =(Long) getDao().uniqueQueryByHql(hql, Integer.valueOf(uids[i]),roleId);
	        if (total==0) {
	            lis.add(new PermissionUserRoleRef(Integer.valueOf(uids[i]), roleId));
            }
        }
	    if(lis.size()==0)return;
	    getDao().saveList(lis);
	}
	/**
	 * 删除角色成员
	 * @param userids
	 */
	public void delRoleMember(Integer userids[]){
        String hql ="delete  PermissionUserRoleRef where id in (:ids) ";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ids", userids);
        getDao().executeHQL(hql, map);
        
       /* Query q = getDao().getSession().createQuery(hql);
        q.setParameterList("ids", userids);
        int affected=q.executeUpdate();
        System.out.println(affected);*/
    }
}
